﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Data
{
    using SharpSoft.Data.Expressions;
    using SharpSoft.Data.GSQL;
    public class SqliteTextGenerator : SQLTextGenerator
    {
        public override string SafetiyStartChar => "[";
        public override string SafetiyEndChar => "]";

        public override string LastAutoId => "LAST_INSERT_ROWID()";

        public override string GetNow => "(datetime('now', 'localtime'))";


        protected override string ProcessColumnDefine(ColumnDefine columnDefine)
        {
            columnDefine.Comment = null;//SQLITE不支持列备注
            return base.ProcessColumnDefine(columnDefine);
        }

        protected override string ColumnAutoincrement()
        {
            return "AUTOINCREMENT";
        }

        protected override string ProcessDataType(DataType dataType)
        {
            if (dataType == DataType.Int || dataType == DataType.Long)
            {
                return "INTEGER";
            }
            else if (dataType== DataType.JSON)
            {
                return "TEXT";
            }
            return base.ProcessDataType(dataType);
        }

        protected override string ProcessExpression(BooleanExpression BO)
        {
            return BO.Content ? "1" : "0";
        }

        protected override NativeSQLCommandScript ProcessStatement(CreateTableStatement statement)
        {
            return base.ProcessStatement(statement);
        }

        protected override string ProcessConstraintDefine(ConstraintDefine constraintDefine)
        {
            StringBuilder sb = new StringBuilder();
            if (constraintDefine.Name != null)
            {//与其他数据库不同的是 SQLITE在没有为约束指定名称时不允许出现“CONSTRAINT”关键字
                sb.Append("CONSTRAINT ");
                sb.Append(ProcessExpression(constraintDefine.Name))
                    .Append(" ");
            }
            sb.Append(ProcessConstraintType(constraintDefine.Type));
            sb.Append("(");
            List<string> list = new List<string>();
            foreach (var item in constraintDefine.Columns)
            {
                list.Add(ProcessExpression(item));
            }
            sb.Append(string.Join(",", list.ToArray()));
            sb.Append(")");
            if (constraintDefine.References != null)
            {
                sb.Append("References ");
                sb.Append(ProcessExpression(constraintDefine.References.TableName));
                sb.Append("(");
                list = new List<string>();
                foreach (var item in constraintDefine.References.Columns)
                {
                    list.Add(ProcessExpression(item));
                }
                sb.Append(string.Join(",", list.ToArray()));
                sb.Append(")");
            }

            return sb.ToString();
        }
    }
}
